<template>
  <div class="school_infs">
    <Card>
      <p slot="title">
        <Icon type="navicon-round"></Icon>
        教师考勤设置
      </p>
      <Row type="flex" justify="space-between">
        <div>
          <div class="db_inline">
            标题：
            <Input v-model="searchparam.title" @on-change="queryFn" placeholder="标题关键字"
                   style="width: 140px;margin-right: 4px;"/>
            <div class="db_inline">
          <span @click="queryFn">
              			<Button type="info"><Icon type="search"></Icon>搜索</Button>
        			</span>
              <span @click="restFn">
              			<Button type="ghost"><Icon type="refresh"></Icon>刷新</Button>
        			</span>
            </div>
          </div>
        </div>
        <div class="control">
          <Button @click="addFn" type="info">
            <Icon type="plus-round"></Icon>
            <span>添加</span>
          </Button>
          <slot name="operation"></slot>
        </div>
      </Row>
      <Row class="margin-top-10">
        <Table :height='tableHeight' ref="backgroundTable" :columns="dataColumns" :data="dataTable"></Table>
      </Row>
      <Row type="flex" justify="end" class="footer">
        <div class="margin-top-10">
          <Page :total="searchparam.total" :current="searchparam.current" :page-size="searchparam.size"
                @on-change="pageChange" show-elevator></Page>
        </div>
      </Row>
    </Card>
    <Modal v-model="modal.visible" :title="modal.title" v-on:on-cancel="cancelFn" :mask-closable="false" width="680"
           v-on:on-ok="submitFn">
      <Form ref="Form" :model="modal.form" :label-width="100" :rules="modal.rules">
        <FormItem label="标题" prop="title">
          <Input v-model="modal.form.title" placeholder="请输入考勤标题（如夏季考勤）" style="width:73%"/>
        </FormItem>
        <FormItem
          v-for="(item, index) in modal.form.items"
          :key="index"
          :label="'名称'">
          <Row>
            <Col span="18">
              <Select v-model="item.name" style="width:120px">
                <Option v-for="item in typeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
              <Time-picker v-model="item.startTime" style="width: 110px" placeholder="开始时间"></Time-picker>
              至
              <Time-picker v-model="item.endTime" style="width: 110px" placeholder="结束时间"></Time-picker>
            </Col>
            <Col span="4">
              <Button @click="handleRemove(item)">删除</Button>
            </Col>
          </Row>
        </FormItem>
        <FormItem>
          <Row>
            <Col span="12">
              <Button @click="handleAdd" icon="plus-round">添加规则</Button>
            </Col>
          </Row>
        </FormItem>
        <label><strong>例子 </strong><label style="margin-left: 50px">名称：正常上班；时间：08:00:00至08:15:00</label>，表示在该时间段内打卡算正常上班</label>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelFn">取消</Button>
        <Button type="primary" @click="submitFn" :loading="modal.loading">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import API from "@/api/api";
  import VmBtable from "@/components/vm/vm-btable";
  import vueUpload from "@/components/views/upload/Upload";
  import Cookie from "js-cookie"

  export default {
    name: "Background",
    components: {
      VmBtable,
      vueUpload,
    },
    data() {
      return {
        cutHeight: 280,
        tableHeight: 640,
        loginType: Cookie.getJSON('loginType'),
        typeList: [
          {'id': '正常上班', 'name': '正常上班'},
          {'id': '迟到', 'name': '迟到'},
          {'id': '旷工', 'name': '旷工'},
          {'id': '早退', 'name': '早退'},
          {'id': '正常下班', 'name': '正常下班'},
        ],
        searchparam: {
          current: 1,
          size: 20,
          title: '',
        },
        dataColumns: [{
          type: 'index',
          title: '序号',
          align: 'center',
          minWidth: 60
        },
          {
            title: '名称',
            key: 'title',
            minWidth: 160,
            align: 'center'
          },
          {
            title: '创建时间',
            key: 'createTime',
            minWidth: 150,
            align: 'center',
          }, {
            title: '状态',
            key: 'status',
            minWidth: 150,
            align: 'center',
            render: (h, param) => {
              let status = param.row.status;
              let str = '停用';
              let color = 'orange';
              if (status === 1) {
                str = '启用';
                color = 'green'
              }
              return h('div', {style: {color: color}}, str);
            }
          },
          {
            title: '操作',
            align: 'center',
            minWidth: 200,
            render: (h, params) => {
              let btn = [];
              let startBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.startFn(params.row)
                  }
                }
              }, '启用');
              let stopBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.stopFn(params.row)
                  }
                }
              }, '停用');
              let editBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.editFn(params.row)
                  }
                }
              }, '编辑');
              let dleBtn = h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.deleteFn(params.row)
                  }
                }
              }, '删除');
              let status = params.row.status;
              if (status === 1) {
                btn = [stopBtn, editBtn, dleBtn]
              } else {
                btn = [startBtn, editBtn, dleBtn]
              }
              return h('div', btn);
            }
          }
        ],
        modal: {
          title: '',
          visible: false,
          loading: false,
          form: {
            id: '',
            title: '',
            items: [
              {
                name: '',
                startTime: '',
                endTime: ''
              }
            ]
          },
          rules: {
            'title': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }]
          }
        },
        dataTable: [],
      }
    },
    methods: {
      handleAdd() {
        this.modal.form.items.push({
          value: '',
          bTime: '',
          eTime: ''
        });
      },
      handleRemove(item) {
        let index = this.modal.form.items.indexOf(item);
        this.modal.form.items.splice(index);
        if (item.id) {
          API.deleteConfig(item.id);
        }
      },
      addFn() {
        Object.assign(this.modal, {
          visible: true,
          title: '新增考勤规则',
          loading: false,
        });
      },
      stopFn(atd) {
        API.startOrStopAtd(atd).then(resp => {
          this.queryFn();
        })
      },
      startFn(atd) {
        if (atd.items.length === 0) {
          this.$Message.warning('未设置有效考勤！');
          return;
        }
        API.startOrStopAtd(atd).then(resp => {
          this.queryFn();
        })
      },
      queryFn() {
        API.fetchAtd(this.searchparam).then(resp => {
          this.dataTable = resp.data.records;
          this.searchparam.total = resp.data.total;
          this.searchparam.current = resp.data.current;
        })
      },
      pageChange(val) {
        this.searchparam.current = val;
        this.queryFn();
      },
      restFn() {
        this.searchparam.title = '';
        this.searchparam.current = 1;
        this.queryFn();
      },
      deleteFn(device) {
        this.$Modal.confirm({
          title: '警告',
          content: '是否删除该教师考勤设置',
          onOk: () => {
            API.deleteAtd(device.id).then(resp => {
              this.queryFn();
            })
          }
        })
      },

      editFn(atd) {
        Object.assign(this.modal, {
          visible: true,
          title: '编辑规则',
          loading: false,
        });
        Object.assign(this.modal.form, atd);
      },
      cancelFn() {
        Object.assign(this.modal, {
          visible: false,
          title: '编辑设备',
          loading: false,
        })
      },
      completeFn() {
        Object.assign(this.modal, {
          visible: false,
          loading: false,
          form: {
            title: '',
            items: [
              {
                name: '',
                startTime: '',
                endTime: ''
              }
            ]
          }
        });
      },
      submitFn() {
        this.$refs.Form.validate(valid => {
          if (valid) {
            this.modal.loading = true;
            let data = Object.assign(this.modal.form);
            if (data.id) {
              API.updateAtd(data).then(resp => {
                this.completeFn();
                this.queryFn();
              })
            } else {
              API.createAtd(data).then(resp => {
                this.completeFn();
                this.queryFn();
              })
            }
          }
        })
      },
      setHeight() {
        this.tableHeight = window.innerHeight - this.$refs.backgroundTable.$el.offsetTop - this.cutHeight;
      }
    },
    mounted() {
      this.queryFn();
      this.setHeight();
    }
  }
</script>

<style scoped>

</style>
